package com.xm.springboot.controller;

import com.xm.springboot.exception.UserNotExistException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class MyExceptionHandler {

    // 1. 无论 浏览器客户端都返回 JSON
/*
    @ResponseBody
    @ExceptionHandler(UserNotExistException.class)
    public Map<String, Object> handelrException(Exception e) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 502);
        map.put("message", e.getMessage());
        return map;
    }
*/

    // 2. 转发到 `/error` 进行自适应响应处理
/*    @ExceptionHandler(UserNotExistException.class)
    public String hanlrException(Exception e, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        // 传入我们自己的错误码, 进入自定义页面
        *//**
         * 		Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
         *//*
        request.setAttribute("javax.servlet.error.status_code", 520);

        map.put("code", 502);
        map.put("message", e.getMessage());
        return "forward:/error";
    }*/

    // 3. 将我们的定制的数据携带出去
    @ExceptionHandler(UserNotExistException.class)
    public String hanlrException(Exception e, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        // 传入我们自己的错误码, 进入自定义页面
        /**
         * 		Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
         */
        request.setAttribute("javax.servlet.error.status_code", 520);

        map.put("code", "user.notexist");
        map.put("message", "用户出错了");

        request.setAttribute("ext", map);

        return "forward:/error";
    }

}
